import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import { format } from "date-fns";
// 导入 API 服务层和工具函数
import {
  diseaseService,
  drugService,
  informationService,
  homeService,
  handleApiResponse,
  handleApiError,
} from "../../utils/api";
// 导入类型定义
import type {
  HomeState,
  BannerItem,
  KnowledgeNavItem,
  KnowledgeItem,
  KnowledgeDetail,
  DragNavItem,
  DragItem,
  DragDetail,
  DoctorItem,
  InformationNavItem,
  InformationItem,
  InformationDetail,
  ApiResponse,
  DoctorListParams,
  KnowledgeListParams,
  KnowledgeDetailParams,
  DragListParams,
  DragDetailParams,
  InformationListParams,
  InformationDetailParams,
} from "../../type/store";

// ==================== 异步 Action Creator 定义 ====================

// 获取轮播图数据
export const getBannerList = createAsyncThunk(
  "home/getBannerList",
  async (): Promise<BannerItem[]> => {
    try {
      const response = await homeService.getBannerList();
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取轮播图数据失败");
    }
  }
);

// 获取问诊医生列表
export const getConsultationDoctors = createAsyncThunk(
  "home/getConsultationDoctors",
  async (params: DoctorListParams): Promise<DoctorItem[]> => {
    try {
      const response = await homeService.getConsultationDoctors(params);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取医生列表失败");
    }
  }
);

// 获取常见病症分类导航
export const getAknowledgeNav = createAsyncThunk(
  "home/getAknowledgeNav",
  async (): Promise<KnowledgeNavItem[]> => {
    try {
      const response = await diseaseService.getDiseaseCategories();
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取病症导航失败");
    }
  }
);
// 获取常见病症列表数据
export const getAknowledgeList = createAsyncThunk(
  "home/getAknowledgeList",
  async (id: number): Promise<KnowledgeItem[]> => {
    try {
      const response = await diseaseService.getDiseaseList(id);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取病症列表失败");
    }
  }
);

// 获取常见病症详情
export const getAknowledgeDetail = createAsyncThunk(
  "getAknowledgeDetail",
  async (id: number) => {
    try {
      const response = await diseaseService.getDiseaseDetail(id);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取病症详情失败");
    }
  }
);
// 获取常用药品分类导航
export const getDragNav = createAsyncThunk("getDragNav", async () => {
  try {
    const response = await drugService.getDrugCategories();
    return handleApiResponse(response);
  } catch (error: any) {
    return Promise.reject(handleApiError(error) || "获取药品分类失败");
  }
});

// 获取常用药品列表数据
export const getDragList = createAsyncThunk(
  "getDragList",
  async (params: object) => {
    try {
      const response = await drugService.getDrugList(params as any);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取药品列表失败");
    }
  }
);
// 获取常用药品详情
export const getDragDetail = createAsyncThunk(
  "getDragDetail",
  async (id: number) => {
    try {
      const response = await drugService.getDrugDetail(id);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取药品详情失败");
    }
  }
);

// 获取资讯分类导航
export const getInformationNav = createAsyncThunk(
  "informationNav",
  async () => {
    try {
      const response = await informationService.getInformationCategories();
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取资讯分类失败");
    }
  }
);
// 获取资讯列表数据
export const getInformationList = createAsyncThunk(
  "informationList",
  async (params: object) => {
    try {
      const response = await informationService.getInformationList(
        params as any
      );
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取资讯列表失败");
    }
  }
);

// 获取资讯详情数据
export const getInformationDetail = createAsyncThunk(
  "informationDetail",
  async (infoId: number) => {
    try {
      const response = await informationService.getInformationDetail(infoId);
      return handleApiResponse(response);
    } catch (error: any) {
      return Promise.reject(handleApiError(error) || "获取资讯详情失败");
    }
  }
);

// ==================== Redux Slice 定义 ====================

const HomeSlice = createSlice({
  name: "home",
  initialState: {
    count: 1,
    status: "idle", // 'idle' | 'loading' | 'succeeded' | 'failed'
    error: "",

    // 轮播图数据
    banners: [],

    // 问诊医生列表
    consultationDoctors: [],

    // 常见病症相关数据
    knowledgeNav: [], // 病症分类导航
    knowledgeList: [], // 病症列表数据
    knowledgeDetail: {
      // 病症详情数据
      id: 0,
      title: "",
      content: "",
      imageUrl: "",
      createTime: "",
      updateTime: "",
    },

    // 常用药品相关数据
    dragNav: [], // 药品分类导航
    dragList: [], // 药品列表数据
    dragDetail: {
      // 药品详情数据
      id: 0,
      title: "",
      content: "",
      imageUrl: "",
      createTime: "",
      updateTime: "",
    },

    // 资讯相关数据
    informaitionNavs: [], // 资讯分类导航
    informaitionList: [], // 资讯列表数据
    lastPayloadLength: 0, // 每次请求返回的payload长度
    informaitiondetail: {
      // 资讯详情数据
      id: 0,
      title: "",
      content: "",
      imageUrl: "",
      createTime: "",
      updateTime: "",
    },
  } as unknown as HomeState,
  // 同步 Reducer 函数
  reducers: {
    // 增加购物车数量（示例函数）
    addCart(state, action: PayloadAction<number>) {
      state.count += action.payload;
    },

    // 清空资讯列表
    clearList(state) {
      state.informaitionList = [];
    },

    // 格式化资讯详情的时间戳
    changeTime(state: any) {
      const newTime = format(
        state.informaitiondetail.releaseTime,
        "yyyy-MM-dd HH:mm:ss"
      );
      console.log(newTime);

      state.informaitiondetail.releaseTime = newTime;
    },
    resetPayloadLength(state) {
      state.lastPayloadLength = 0;
    },
  },
  // 异步处理 - 使用 addMatcher 统一处理所有异步操作的成功状态
  extraReducers: (builder) => {
    // 通用的成功状态处理 - 匹配所有以 '/fulfilled' 结尾的 action
    builder.addMatcher(
      (action) => action.type.endsWith("/fulfilled"),
      (state, action: any) => {
        // 统一设置成功状态
        state.status = "succeeded";

        // 根据不同的 action 类型，更新对应的状态数据
        switch (action.type) {
          // 轮播图数据获取成功
          case getBannerList.fulfilled.type:
            state.banners = action.payload;
            break;

          // 问诊医生列表获取成功
          case getConsultationDoctors.fulfilled.type:
            state.consultationDoctors = action.payload;
            break;

          // 资讯分类导航获取成功
          case getInformationNav.fulfilled.type:
            state.informaitionNavs =
              action.payload as unknown as InformationNavItem[];
            break;

          // 资讯列表数据获取成功 - 支持分页加载（追加数据）
          case getInformationList.fulfilled.type:
            if (Array.isArray(action.payload) && action.payload.length) {
              // 将新数据追加到现有列表末尾，实现分页加载
              state.informaitionList = state.informaitionList.concat(
                action.payload as unknown as InformationItem[]
              );
              // 记录payload长度
              state.lastPayloadLength = action.payload.length;
            }
            break;

          // 资讯详情获取成功 - 包含时间格式化处理
          case getInformationDetail.fulfilled.type:
            state.informaitiondetail =
              action.payload as unknown as InformationDetail;
            // 格式化发布时间显示
            if (
              state.informaitiondetail.releaseTime &&
              typeof state.informaitiondetail.releaseTime === "string"
            ) {
              const newTime = format(
                state.informaitiondetail.releaseTime,
                "yyyy-MM-dd HH:mm:ss"
              );
              state.informaitiondetail.releaseTime = newTime;
            }
            break;

          // 常见病症分类导航获取成功
          case getAknowledgeNav.fulfilled.type:
            state.knowledgeNav = action.payload;
            break;

          // 常见病症列表数据获取成功
          case getAknowledgeList.fulfilled.type:
            state.knowledgeList = action.payload;
            break;

          // 常见病症详情获取成功
          case getAknowledgeDetail.fulfilled.type:
            state.knowledgeDetail =
              (action.payload as unknown as KnowledgeDetail) || {};
            break;

          // 常用药品分类导航获取成功
          case getDragNav.fulfilled.type:
            state.dragNav = (action.payload as unknown as DragNavItem[]) || [];
            break;

          // 常用药品列表数据获取成功
          case getDragList.fulfilled.type:
            state.dragList = (action.payload as unknown as DragItem[]) || [];
            break;

          // 常用药品详情获取成功
          case getDragDetail.fulfilled.type:
            state.dragDetail = (action.payload as unknown as DragDetail) || {};
            break;
        }
      }
    );
  },
});
export const { addCart, clearList, changeTime,resetPayloadLength } = HomeSlice.actions;
export default HomeSlice.reducer;
